/**
 * @(#) FakeSource.java;
 * <p/>
 * Created on May 27, 2008
 * AUTHOR    ** Danil Glinenko
 * EMAIL     ** dglinenko@gmail.com
 * <p/>
 *
 * Copyright (C) 2008 Danil Glinenko. All rights reserved.
 */

package jacky.lanlan.song.test.db;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

public class HSQL extends RDBMS {
	public HSQL(final String sourceName, final String ymlCfgFilePath) {
		super(sourceName, ymlCfgFilePath);
	}

	@Override
	public void loadSchemaFile(final String schemaFilePath) {
		try {
			final String sqlSchema = loadSQLFromFile(schemaFilePath);
			applySql(sqlSchema);
		}
		catch (SQLException e) {
			throw new RuntimeException("Unable to apply schema file: " + schemaFilePath + " check your SQL schema file.", e);
		}
		catch (IOException e) {
			throw new RuntimeException("Unable to load schema file: " + schemaFilePath, e);
		}
	}

	private String loadSQLFromFile(final String path) throws IOException {
		// load file and return its contents as String
		final InputStream file = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
		if (file != null) {
			final byte[] b = new byte[file.available()];
			file.read(b);
			file.close();
			return new String(b);
		}
		throw new RuntimeException("File: " + path + " cannot be found or loaded:");
	}

	/**
	 * Runs SQL statements on a given sql connection object.
	 * 
	 * @param sql
	 *          SQL statements to run.
	 * @throws SQLException
	 *           if unable to run SQL statements.
	 */
	private void applySql(final String sql) throws SQLException {
		final String[] segments = sql.split(";");
		for (String seg : segments) {
			if (seg.trim().length()!=0) {
				this.runSqlStatement(seg += ";", false);
			}
		}
	}

}
